package com.hgq.jssjyyxt.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgq.jssjyyxt.constant.RedisConstant;
import com.hgq.jssjyyxt.entity.Users;
import com.hgq.jssjyyxt.entity.Users;
import com.hgq.jssjyyxt.enums.RoleEnum;
import com.hgq.jssjyyxt.enums.StateEnum;
import com.hgq.jssjyyxt.service.UsersService;
import com.hgq.jssjyyxt.util.OrderGenerator;
import com.hgq.jssjyyxt.util.Result;

import com.hgq.jssjyyxt.util.ValidToken;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * (Users)表控制层
 *
 * @author makejava
 * @since 2024-04-11 13:53:47
 */
@Transactional(rollbackFor = Exception.class)
@RestController
@RequestMapping("users")
public class UsersController {
    /**
     * 服务对象
     */
    @Resource
    private UsersService usersService;
    @Resource
    RedisTemplate<String, Integer> redisTemplate;

    /**
     * 分页查询
     *
     * @param users 筛选条件
     * @param limit 分页对象
     * @param page  分页对象
     * @return 查询结果
     */
    @GetMapping("findAll")
    public Result findAll(Users users, Integer limit, Integer page) {
        if (limit == null || page == null) {
            return Result.failure("limit和page不能为空");
        }
        return usersService.selectAll(users, limit, page);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param request 请求
     * @return 单条数据
     */
    @GetMapping("getById")
    public Result getById(HttpServletRequest request) {
        Integer id = ValidToken.getIdByToken(request, redisTemplate);
        return Result.success(this.usersService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param users 实体
     * @return 新增结果
     */
    @PostMapping("add")
    public Result add(@RequestBody Users users) {
        //判断是否为空
        if (users == null) {
            return Result.failure("参数不能为空");
        }

        //如果头像为空，则填充默认头像
        String avatar = users.getAvatar();
        if (!StringUtils.hasLength(avatar)) {
            users.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }

        //判断账号是否已经存在
        if (this.usersService.count(new QueryWrapper<Users>().eq("username", users.getUsername())) > 0) {
            return Result.failure("账号已存在");
        }

        users.setPassword("123456");

        if (this.usersService.save(users)) {
            return Result.success("添加成功");
        }
        return Result.failure("添加失败");
    }

    /**
     * 编辑数据
     *
     * @param users 实体
     * @return 编辑结果
     */
    @PostMapping("edit")
    public Result edit(@RequestBody Users users) {
        //判断是否为空
        if (users == null) {
            return Result.failure("参数不能为空");
        }

        if (this.usersService.updateById(users)) {
            return Result.success("修改成功");
        }
        return Result.failure("修改失败");
    }

    /**
     * 删除数据
     *
     * @param data 主键
     * @return 删除是否成功
     */
    @PostMapping("delete")
    public Result deleteById(@RequestBody JSONObject data) {
        //判断id是否为空
        Integer id = data.getInteger("userId");
        if (id == null) {
            return Result.failure("id不能为空");
        }

        if (this.usersService.removeById(id)) {
            return Result.success("删除成功");
        }
        return Result.failure("删除失败");
    }

    @PostMapping("login")
    public Result login(@RequestBody Users users) {
        //判断是否为空
        if (users == null) {
            return Result.failure("参数不能为空");
        }

        //根据账号和角色进行查找
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", users.getUsername());
        Users one = usersService.getOne(usersQueryWrapper);

        if (one == null) {
            return Result.failure("账号不存在,请先注册");
        }

        if (!one.getPassword().equals(users.getPassword())) {
            return Result.failure("密码错误,请重新输入");
        }

        String token = String.valueOf(OrderGenerator.generateOrderNumber());
        redisTemplate.opsForValue().set(token, one.getUserId(), RedisConstant.REDIS_SAVE_DURATION_ONE_DAY, TimeUnit.DAYS);
        return Result.success("登录成功", token);
    }

    @PostMapping("register")
    public Result register(@RequestBody Users users) {
        //判断是否为空
        if (users == null) {
            return Result.failure("参数不能为空");
        }
        users.setAccountBalance(BigDecimal.ZERO);
        users.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");

        //根据账号进行查找
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", users.getUsername());
        Users one = usersService.getOne(usersQueryWrapper);

        if (one != null) {
            return Result.failure("账号已存在,请重新输入");
        }

        if (this.usersService.save(users)) {
            return Result.success("注册成功");
        }
        return Result.failure("注册失败");
    }

}

